package org.fujie.plugin.cloud.face.tencent.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import lombok.SneakyThrows;
import org.fujie.plugin.cloud.comm.constant.ProviderConstant;
import org.fujie.plugin.cloud.core.model.RecognizedIdCardScanRes;
import org.fujie.plugin.cloud.face.provider.server.ProviderService;
import org.fujie.plugin.cloud.face.tencent.config.TencentConfig;
import org.fujie.plugin.cloud.face.tencent.convert.TencentConvert;

/**
 * @author slm
 * @description
 */
public class TencentIdCardServer extends ProviderService<TencentConfig> {

    private final OcrClient ocrClient;

    @SneakyThrows(Exception.class)
    public TencentIdCardServer(TencentConfig config) {
        super(config);

        Credential cred = new Credential(config.getAccessKeyId(),config.getAccessKeySecret());
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(config.getEndpoint());
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        this.ocrClient = new OcrClient(cred, "ap-beijing", clientProfile);

    }

    /**
     * 获取供应商标识
     */
    @Override
    public String getSupplier() {
        return ProviderConstant.TENCENT_CLOUD;
    }

    /**
     * @param frontUrl 国徽面图片网络地址
     * @author sunliming
     * @description 身份证国徽面识别
     */
    @Override
    public RecognizedIdCardScanRes recognizeIdFrontCard(String frontUrl) throws JsonProcessingException {

        try {
             return TencentConvert.ofRes(this.execute(frontUrl),0);
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param backUrl 人像面图片地址
     * @author sunliming
     * @description 身份证人像面识别
     */
    @Override
    public RecognizedIdCardScanRes recognizeIdBackCard(String backUrl) throws JsonProcessingException {
        try {
            return TencentConvert.ofRes(this.execute(backUrl),0);
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
    }

    private IDCardOCRResponse execute(String imageUrl) throws TencentCloudSDKException {

        IDCardOCRRequest req = new IDCardOCRRequest();
        req.setImageUrl(imageUrl);
        return ocrClient.IDCardOCR(req);
    }
}
